package us.congcong.rsshunter.service;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Service;
import us.congcong.rsshunter.config.LocalConstant;
import us.congcong.rsshunter.model.SampleChannel;
import us.congcong.rsshunter.model.SampleContent;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class ToutiaoRssService {
	public static void main(String[] args) {
		ToutiaoRssService wr = new ToutiaoRssService();
		wr.produceRss();
	}

	private static String baseUrl = "https://toutiao.io";

	public Map<String, Object> produceRss() {
		Map<String, Object> info = new HashMap<String,Object>();
		
		SampleChannel channel = new SampleChannel();
		List<SampleContent> list = new ArrayList<SampleContent>();
		
		Document doc = null;
		try {
			doc = Jsoup.connect(baseUrl).get();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		if(doc != null){
			channel.setTitle("开发者头条");
			channel.setDescription(LocalConstant.authorInfo);
			channel.setLink(baseUrl);
			
			Elements items = doc.getElementsByClass("post");

			for (Element item : items) {
				Element titleE = item.select("div.content").first().select("h3.title").first();
				//Content
                String title = titleE.text();
				String url = titleE.select("a").first().attr("href");

                SampleContent content = new SampleContent();
				try {
                    String text = Jsoup.connect(baseUrl + url).get().html();
                    //here shoud be html
                    content.setSummary(text);
                }catch (IOException e) {
				    e.printStackTrace();
                }

				content.setTitle(title);
				content.setCreatedDate(new Date());
				content.setUrl(baseUrl + url);
				
				list.add(content);
			}
		} else {
			return null;
		}
		info.put("channel", channel);
		info.put("items", list);
		return info;
	}

}
